#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define FIFO_FILE "fifo"
#define PATH "."
#define FILENAME "fifo"

// 宏替换, 打印错误信息
// “\”是续行符
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

struct Namedfifo
{
public:
    Namedfifo(const std::string path, const std::string name)
        : _path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            // std::cerr << "mkfifo error" << std::endl;
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "mkfifo success" << std::endl;
        }
    }
    ~Namedfifo()
    {
        // 删除管道文件
        int m = unlink(_fifoname.c_str());
        if (m == 0)
        {
            std::cout << "remove fifo success" << std::endl;
        }
        else
        {
            // std::cout << "remove fifo failed" << std::endl;
            ERR_EXIT("unlink");
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            // std::cerr << "open fifo error" << std::endl;
            // return;
            ERR_EXIT("open");
        }
        std::cout << "open fifo success" << std::endl;
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            // std::cerr << "open fifo error" << std::endl;
            // return;
            ERR_EXIT("open");
        }
        std::cout << "open fifo success" << std::endl;
    }

    void Wakeup()
    {
        // 无论写入什么内容，一个字符就行
        char c = 'c';
        write(_fd, &c, 1);
    }
    bool Wait()
    {
        // 我们要求: 一次只能读取一个字符
        char c;
        int number = read(_fd, &c, 1);
        if (c > 0)
            return true;
        return false;
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~FileOper() 
    {
        // 删除管道文件
        int n = unlink(_fifoname.c_str());
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};
